//***定义为全局变量***
//获取驱动信息
var driver = JSON.parse($("#dirverJson").text());

//获取驱动的Logo,返回logo路径
function getDriverLogo(mapping){
	var logo = "";
	switch (mapping.connector) {
	case ConnectorConstantDatabase:
		//如果是数据库类型
		var className = mapping.config.driverClassName;
		logo = DriverConnectorConstant[ConnectorConstantDatabase]['image'][className];
		break;
	case ConnectorConstantLdap:
		//如果是Ldap类型
		logo = DriverConnectorConstant[ConnectorConstantLdap]['image'];
		break;
	case ConnectorConstantWebService:
		//如果是WebService类型
		logo = DriverConnectorConstant[ConnectorConstantWebService]['image'];
		break;
	default:
		break;
	}
	return logo;
}

//显示驱动数据源和目标源
function showDriverEditInfo(driver) {
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.mappings[0];
	
	// 获取数据源和目标源连接器logo
	var sourceLogo = getDriverLogo(sourceMapping);
	var targetLogo = getDriverLogo(targetMapping);
	$("#sourceLogo").attr("src",sourceLogo);
	$("#targetLogo").attr("src",targetLogo);
	
	// 获取数据源和目标源连接器类型
	var sourceType = DriverConnectorConstant[sourceMapping.connector]['type'];
	var targetType = DriverConnectorConstant[targetMapping.connector]['type'];
	$("#sourceType").text("类型：" + sourceType);
	$("#targetType").text("类型：" + targetType);
	
}

//显示驱动编辑配置（迁移/同步）
function showDriverEditConfig(opr){
	var url = '';
	switch (opr) {
	case 'migration':
		url = $basePath+"/driver/page/driverEditMigration";
		break;
	case 'sync':
		url = $basePath+"/driver/page/driverEditSync";
		break;
	default:
		break;
	}
	if(url != ''){
		$.post(url,function(resp){
			// 加载后端响应视图
			$("#driverEditConfigContainer").html(resp);
		});
	}
}

//绑定修改驱动同步方式切换事件
function bindEventForDriverEditConfig($driverEditConfigChange, driver) {
	// 初始化icheck插件
	$driverEditConfigChange.find("input").iCheck({
		labelHover : false,
		cursor : true,
		radioClass : 'iradio_flat-blue',
	}).on('ifChecked', function(event){
		showDriverEditConfig($(this).val());
	});
	
	var model = 'all'==driver.model ? 0 : 1;
	// 默认渲染数据迁移配置
	$driverEditConfigChange.find("input").eq(model).iCheck("check");
	
	//如果是webservice连接器，隐藏数据迁移radio
	if(driver.sourceMapping.connector != ConnectorConstantWebService){
		$(".driverEditRadioDisplay").removeClass("hidden");
	}else{
		$(".driverEditSyncRadioDisplay").removeClass("hidden");
		$(".driverEditSyncRadioDisplay").after('<div class="col-sm-2"></div>');
	}
	
}

//获取基本信息
function saveDriverConfigCommonProperty(driver) {
	var trs = $("#propertyList").find("tr");
	var sourceFileds = [];
	var targetFileds = [];
	trs.each(function(i, o) {
		var sField = $(this).find("td:eq(0)");
		var tField = $(this).find("td:eq(1)");
		sourceFileds.push({
			"name" : sField.text(),
			"type" : sField.attr("type"),
			"typeName" : sField.attr("typeName")
		});
		targetFileds.push({
			"name" : tField.text(),
			"type" : tField.attr("type"),
			"typeName" : tField.attr("typeName")
		});
	});
	driver.sourceMapping.fileds = sourceFileds;
	driver.mappings[0].fileds = targetFileds;
}

//获取过滤条件
function saveDriverConfigCommonFilter(driver) {
	//过滤条件
	var ands = [];
	var ors = [];
	var trs = $("#conditionList").find("tr");
	trs.each(function(i, o) {
		var combination = $(this).find("td:eq(0)").attr('name');
		var name = $(this).find("td:eq(1)").attr('name');
		var operator = $(this).find("td:eq(2)").attr('name');
		var value = $(this).find("td:eq(3)").attr('name');
		if ("and" == combination) {
			ands.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		} else if ("or" == combination) {
			ors.push({
				"name" : name,
				"operator" : operator,
				"value" : value
			});
		}
	});
	driver.query = {};
	driver.query.and = ands;
	driver.query.or = ors;
}

//获取数据迁移配置
function saveDriverConfigMigration(driver) {	
	//组装基本信息配置
	saveDriverConfigCommonProperty(driver);
	//组装过滤条件配置
	saveDriverConfigCommonFilter(driver);
	//设置为迁移
	driver.model = "all";
}

//获取数据同步增量配置,如果校验失败返回false
function saveDriverConfigSyncStrategy(driver) {	
	driver.policy = {};
	// 判断时候数据库连接器类型
	var sourceMapping = driver.sourceMapping;
	// 增量开关
	var enable = $("#driverStrategyIncrementEnable").find("input[type='checkbox']").val();
	if(sourceMapping.connector==ConnectorConstantDatabase){
		var driverClassName = sourceMapping.config.driverClassName;
		// 获取Mysql配置
		if(driverClassName=='com.mysql.jdbc.Driver'){
			var ip = $("#sourceStrategyIncrementIp").val();
			var port = parseInt($("#sourceStrategyIncrementPort").val());
			var instance = $("#sourceStrategyIncrementInstance").val();
			var database = $("#sourceStrategyIncrementDatabase").val();
			var table = $("#sourceStrategyIncrementTable").val();
			
			//对同步配置表单进行必填校验
			if($("#syncConfigContainer").formValidate()==false){
				return false;
			}
			
			driver.policy.increment = {
				"enable" : enable,
				"type":"mysql",
				"ip" : ip,
				"port" : port,
				"instance" : instance,
				"database" : database,
				"table" : table
			};
			return true;
		}
		
		// 获取Oracle配置
		if(driverClassName=='oracle.jdbc.OracleDriver'){
			var scanAll = $("#sourceStrategyIncrementScanAll").find('[name="scanAll"]:checked').val();
			var dictionary = $("#sourceStrategyIncrementDictionaryPath").val();
			
			//对同步配置表单进行必填校验
			if($("#syncConfigContainer").formValidate()==false){
				return false;
			}
			
			driver.policy.increment = {
				"enable" : enable,
				"type":"oracle",
				"scanAll" : scanAll,
				"dictionary" : dictionary
			};
			return true;
		}
	}else if(sourceMapping.connector==ConnectorConstantLdap){
		// 获取Ldap配置
		driver.policy.increment = {
			"enable" : enable,
			"type" : "ldap",
			"url":$("#ldapStrategyIncrementUrl").val(),
			"base" : $("#ldapStrategyIncrementBase").val(),
			"userDn" : $("#ldapStrategyIncrementUserDn").val(),
			"password" : sourceMapping.config.password,
			"searchScope" : $("#ldapStrategyIncrementSearchScope option:selected").val()
		};
		return true;
	}else if(sourceMapping.connector==ConnectorConstantWebService){
		// 获取Webservice配置
		driver.policy.increment = {
			"enable" : enable,
			"type":"ws"
		};
		return true;
	}
	return false;
}

//获取数据同步配置,如果校验失败返回false
function saveDriverConfigSync(driver) {	
	//组装基本信息配置
	saveDriverConfigCommonProperty(driver);
	//组装过滤条件配置
	saveDriverConfigCommonFilter(driver);
	//组装增量信息配置
	if(!saveDriverConfigSyncStrategy(driver)){
		return false;
	}
	//设置为同步
	driver.model = "increment";
}

//保存驱动配置
function saveDriverConfig(id, driver) {
	id = id.find("input[name='driverEditConfig']:checked").val();
	switch (id) {
	// 数据迁移
	case 'migration':
		saveDriverConfigMigration(driver);
		break;
	// 数据同步
	case 'sync':
		//校验数据同步高级配置，返回null意味着校验失败
		if(saveDriverConfigSync(driver)==false){
			bootGrowl("保存失败,请检查参数.", "danger");
			return false;
		}
		break;
	default:
		break;
	}
	// 保存驱动配置
	$.loadingT(true);
	$.post($basePath + "/driver/update", {
		"mapping" : JSON.stringify(driver)
	}, function(data) {
		$.loadingT(false);
		if (data.success == true) {
			bootGrowl(data.resultValue, "success");
			$initContainer.load($basePath + "/index");
		} else {
			bootGrowl(data.resultValue, "danger");
		}
	});
}

$(function() {
	// 显示驱动编辑信息
	showDriverEditInfo(driver);

	// 加载数据迁移	
	var $driverEditConfigChange = $('#driverEditConfigChange');
	bindEventForDriverEditConfig($driverEditConfigChange, driver);

	// 保存
	$("#driverSubBtn").click(function() {
		saveDriverConfig($driverEditConfigChange, driver);
	});
	// 返回
	$("#driverBackIndexBtn").click(function() {
		// 加载页面
		$initContainer.load($basePath + "/index");
	});
})